<template>
  <div class="header_container">
    <div class="header_img" @click="openDialog">
      <img src="../../common/img/yiyao.jpg" />
    </div>
    <div class="header_search">
      <div class="search_input">
        <input type="text" placeholder="搜索 商品名称" v-model="keywords" />
        <el-button type="danger" icon="el-icon-search" @click="postSearch"></el-button>
      </div>
      <p class="suggestions">
        <a @click="fillSearch('美白')">美白</a>
        <a @click="fillSearch('呵护女性')">呵护女性</a>
        <a @click="fillSearch('健康调理')">健康调理</a>
        <a @click="fillSearch('保护视力')">保护视力</a>
        <a @click="fillSearch('养生保健')">养生保健</a>
      </p>
    </div>
    <div class="shopping_bag">
      <a @click.prevent="goShopCar"><i class="el-icon-shopping-cart-2"></i>&nbsp;&nbsp;我的购物车</a>
    </div>

    <!-- Dialog for 导诊助手 -->
    <el-dialog :visible.sync="dialogVisible" width="50%" custom-class="chat-dialog">
      <div class="chat-header">
        <span v-for="(char, index) in headerText" :key="index" class="animated-char">{{ char }}</span>
      </div>
      <div class="chat-container">
        <div class="chat-messages" ref="chatMessages">
          <div v-for="message in messages" :key="message.id"
            :class="{ 'message-left': message.from === 'bot', 'message-right': message.from === 'user' }">
            <div class="message-content-wrapper">
              <div v-if="message.from === 'bot' && message.showAvatar" class="avatar">
                <img src="../../common/img/robot.png" />
              </div>
              <div class="message-content">
                <div v-if="message.type === 'text'" class="message-text">{{ message.content }}</div>
                <div v-if="message.type === 'product'" class="message-product">
                  <img :src="message.product.thumb_url" class="product-image"
                    @click="goToProduct(message.product.goods_id)" />
                  <div class="product-info">
                    <span>{{ message.product.short_name }}</span>
                    <time class="time">{{ message.product.sales_tip }}</time>
                    <el-button type="text" class="button"
                      @click="goToProduct(message.product.goods_id)">查看详情</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <el-input v-model="userInput" placeholder="请输入您的问题或病情">
            <template slot="append">
              <img src="../../common/img/send.png" class="send-icon" @click="sendMessage" />
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from "element-ui";
import { mapState } from "vuex";
import axios from 'axios';

export default {
  data() {
    return {
      keywords: "",
      dialogVisible: false,
      userInput: "",
      messages: [],
      botMessage: "",
      headerText: "导诊助手",
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    goShopCar() {
      if (this.userInfo.id) {
        this.$router.replace("/shopcar");
      } else {
        MessageBox({
          type: "info",
          message: "请先登录!",
          showClose: true,
        });
      }
    },
    async postSearch() {
      if (this.keywords) {
        let keywords = this.keywords;
        await this.$store.dispatch("reqSearch", { keywords });
        this.$router.replace("/searchdetail");
      }
    },
    async fillSearch(keyword) {
      this.keywords = keyword;
      await this.$store.dispatch("reqSearch", { keywords: keyword });
      this.$router.replace("/searchdetail");
    },
    openDialog() {
      this.dialogVisible = true;
      this.animateHeader();
    },
    async sendMessage() {
      if (this.userInput.trim() === "") return;

      // 用户发送消息
      this.messages.push({
        id: Date.now(),
        from: "user",
        type: "text",
        content: this.userInput,
      });

      // 保存用户输入
      const userQuery = this.userInput;
      this.userInput = "";

      this.$nextTick(() => {
        this.scrollToBottom();
      });

      try {
        const BASE_URL = '/api';  // 防跨域
        const response = await axios.post(BASE_URL + '/api/searchgoods', { keywords: userQuery });
        if (response.data.success_code === 200 && response.data.message.length > 0) {
          // 添加推荐商品提示
          this.typeBotMessage("根据您的描述，为您推荐以下商品：", () => {
            // 延时添加商品信息
            response.data.message.forEach((product, index) => {
              setTimeout(() => {
                this.messages.push({
                  id: Date.now() + Math.random(),
                  from: "bot",
                  type: "product",
                  product: product,
                  showAvatar: false
                });
                this.$nextTick(() => {
                  this.scrollToBottom();
                });
              }, 1000 * (index + 1));
            });
          });
        } else {
          setTimeout(() => {
            this.messages.push({
              id: Date.now(),
              from: "bot",
              type: "text",
              content: "很抱歉，根据您的描述，商城中暂无您所需要的商品",
              showAvatar: true
            });
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          }, 1000);
        }
      } catch (error) {
        console.error("搜索商品失败:", error);
        this.messages.push({
          id: Date.now(),
          from: "bot",
          type: "text",
          content: "搜索商品失败，请稍后再试",
          showAvatar: true
        });
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    typeBotMessage(message, callback) {
      let index = 0;
      this.botMessage = "";
      const interval = setInterval(() => {
        if (index < message.length) {
          this.botMessage += message[index];
          if (this.messages.length === 0 || this.messages[this.messages.length - 1].from !== "bot") {
            this.messages.push({
              id: Date.now() + Math.random(),
              from: "bot",
              type: "text",
              content: this.botMessage,
              showAvatar: true
            });
          } else {
            this.messages[this.messages.length - 1].content = this.botMessage;
          }
          this.$nextTick(() => {
            this.scrollToBottom();
          });
          index++;
        } else {
          clearInterval(interval);
          if (callback) callback();
        }
      }, 100);
    },
    goToProduct(id) {
      this.dialogVisible = false; // 关闭对话框
      setTimeout(() => { // 确保对话框关闭后再跳转
        this.$router.replace("/goods/" + id);
      }, 300); // 根据实际情况调整延迟时间
    },
    animateHeader() {
      this.headerText = "导诊助手".split("");
    },
    scrollToBottom() {
      const container = this.$refs.chatMessages;
      container.scrollTop = container.scrollHeight;
    }
  },
};
</script>

<style scoped>
/*头部搜索区*/
.header_container {
  position: relative;
  width: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-around;
}

/*商城标识图片区域*/
.header_img {
  width: 100px;
  height: 100px;
  border: 1px solid darkgray;
  box-shadow: 2px 4px 15px rgba(45, 45, 45, 0.15);
  border-radius: 50%;
  margin-left: -100px;
}

.header_img img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

/*鼠标移入图片实现3d动画*/
.header_img:hover {
  transform-style: preserve-3d;
  transform: rotateY(360deg);
  transition: all 1500ms;
  -moz-transform-style: preserve-3d;
  -moz-transform: rotateY(45deg);
  -moz-transition: all 1500ms;
}

.header_search {
  flex: 1;
  max-width: 600px;
  width: 100%;
  margin-top: 30px;
}

.header_search .search_input {
  display: flex;
  align-items: center;
}

.header_search input {
  flex: 1;
  padding-left: 10px;
  height: 35px;
  font-size: 14px;
  line-height: 35px;
  border: 2px solid #ff0236;
  border-right: none;
  outline: none;
}

.header_search button.el-button.el-button--danger {
  padding: 0;
  width: 60px;
  height: 35px;
  font-size: 18px;
  border-radius: 0;
  outline: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header_search .suggestions {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.header_search .suggestions a {
  display: inline-block;
  padding: 5px 10px;
  font-size: 12px;
  color: #999;
  cursor: pointer;
}

.header_search .suggestions a:hover {
  color: red;
}

/*头部的购物车标记区域*/
.shopping_bag {
  margin: 10px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
}

.shopping_bag a {
  color: red;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header_container {
    flex-direction: column;
    align-items: center;
  }

  .header_img {
    width: 80px;
    height: 80px;
  }

  .header_search {
    max-width: 100%;
  }

  .header_search input {
    width: calc(100% - 60px);
  }

  .shopping_bag {
    width: 100%;
    text-align: center;
    margin-top: 10px;
  }
}

/* 导诊助手对话框样式 */
.chat-dialog {
  padding: 0;
}

.chat-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  padding: 10px 0;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e6e6e6;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  background-image: url('../../common/img/robot_logo2.png');
  background-repeat: no-repeat;
  background-position: center;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: rgba(249, 249, 249, 0.8);
  border-bottom: 1px solid #e6e6e6;
}

.chat-input {
  display: flex;
  padding: 10px;
  background-color: #fff;
}

.send-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.message-left {
  margin-bottom: 10px;
  justify-content: flex-start;
}

.message-right {
  display: flex;
  margin-bottom: 20px;
  justify-content: flex-end;
}

.message-content-wrapper {
  display: flex;
  align-items: flex-start;
}

.message-content {
  display: flex;
  align-items: center;
  margin: 0 10px;
}

.message-text {
  padding: 10px;
  background-color: #e0f7fa;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  word-break: break-all;
  white-space: pre-wrap;
}

.message-product {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 310px;
  height: 210px;
  margin-left: 30px;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 10px;
}

.product-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.time {
  font-size: 12px;
  color: #999;
}

.button {
  margin-top: 5px;
  color: #409eff;
  cursor: pointer;
}

.animated-char {
  display: inline-block;
  opacity: 0;
  animation: fadeIn 0.5s forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.el-card {
  width: 100%;
  background-color: #fff;
  border: none;
}
</style>
